﻿#pragma execution_character_set("utf-8")
#include "ui/devicesearchwidget.h"
#include "core/discovery/discoveryclient.h"
#include "media/ffmpeg/ffmpeg.h"
#include <QApplication>
#include <QTextCodec>
#include <QNetworkProxy>
#include <QDebug>
#include <QLoggingCategory>

#ifdef _WIN32
#include <windows.h>

// 自定义调试输出处理器，只输出设备搜索相关信息
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 过滤Windows系统错误信息
    if (msg.contains("nlansp_c.dll") ||
        msg.contains("namespaceserviceprovider.cpp") ||
        msg.contains("此服务不存在") ||
        msg.contains("LogHr") ||
        msg.contains("onecore\\net")) {
        return; // 忽略这些系统错误
    }
    
    // 只输出包含设备搜索关键词的调试信息
    if (msg.contains("Search", Qt::CaseInsensitive) ||
        msg.contains("Discovery", Qt::CaseInsensitive) ||
        msg.contains("Device", Qt::CaseInsensitive) ||
        msg.contains("UDP", Qt::CaseInsensitive) ||
        msg.contains("Multicast", Qt::CaseInsensitive) ||
        msg.contains("ONVIF", Qt::CaseInsensitive) ||
        msg.contains("HTTP", Qt::CaseInsensitive) ||
        msg.contains("Found", Qt::CaseInsensitive) ||
        msg.contains("LibUV", Qt::CaseInsensitive)) {
        
        QString txt;
        switch (type) {
        case QtDebugMsg:    txt = QString("Debug: %1").arg(msg); break;
        case QtWarningMsg:  txt = QString("Warning: %1").arg(msg); break;
        case QtCriticalMsg: txt = QString("Critical: %1").arg(msg); break;
        case QtFatalMsg:    txt = QString("Fatal: %1").arg(msg); break;
        }
        
        // 输出到VS调试窗口
        OutputDebugStringA((txt + "\n").toLocal8Bit().data());
    }
}
#endif

int main(int argc, char *argv[])
{
#ifdef _WIN32
    // 安装自定义消息处理器，只输出设备搜索相关信息
    qInstallMessageHandler(myMessageOutput);
#endif

    #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
    QApplication a(argc, argv);
    
    QFont font;
    font.setFamily("Microsoft Yahei");
    font.setPixelSize(13);
    a.setFont(font);
    
    QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
    
    // 初始化FFmpeg库
    FFmpegThread::initlib();
    
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
#if _MSC_VER
    QTextCodec *codec = QTextCodec::codecForName("gbk");
#else
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
#endif
    QTextCodec::setCodecForLocale(codec);
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
#else
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
    QTextCodec::setCodecForLocale(codec);
#endif

    DeviceSearchWidget w;
    w.setWindowTitle("IPC Camera Device Search Tool");
    w.resize(1200, 800);
    w.show();


    return a.exec();
}
